#include "gpxparser.h"

#include <iostream>
using std::cout;
using std::endl;
#include <algorithm>

GPXParser::GPXParser()
{
}

void GPXParser::parseFile(QString fileName)
{
    QFile* xmlFile = new QFile(fileName);

    if (!xmlFile->open(QIODevice::ReadOnly | QIODevice::Text))
    {
        cout << "Couldn't open file " << fileName.toStdString() << endl;
        return;
    }

    QXmlStreamReader xml(xmlFile);

    while(!xml.atEnd() && !xml.hasError())
    {
        QXmlStreamReader::TokenType token = xml.readNext();

        if(token == QXmlStreamReader::StartDocument)
        {
            continue;
        }

        if(token == QXmlStreamReader::StartElement)
        {
            if(xml.name() == "gpx")
            {
                continue;
            }

            // If it's named wpt, then this is the start of what we want.
            if(xml.name() == "wpt")
            {
                parseWaypoint(xml);
            }
        }
    }

    // Okay, now let's sort the list of caches
    std::sort(caches.begin(), caches.end(), cacheSorter);
}

void GPXParser::parseWaypoint(QXmlStreamReader& xml)
{
    if(xml.tokenType() != QXmlStreamReader::StartElement && xml.name() == "wpt")
    {
        return;
    }

    xml.readNext();

    cache newCache;

    while(!(xml.tokenType() == QXmlStreamReader::EndElement && xml.name() == "wpt"))
    {
        if(xml.tokenType() == QXmlStreamReader::StartElement)
        {
            if(xml.qualifiedName() == "name")
            {
                xml.readNext();
                newCache.cacheName = xml.text().toString().toStdString();
            }
            else if(xml.name() == "desc")
            {
                xml.readNext();
                newCache.cacheDesc = xml.text().toString().toStdString();
            }
        }

        xml.readNext();
    }

    caches.push_back(newCache);
}

vector<cache> GPXParser::getCaches()
{
    return caches;
}
